﻿ //Copyright (C) <2013>  <jonathan cleeve norton> All Rights Reserved 
//Contact jon.norton@fin-plus.co.uk website <http://www.fin-plus.co.uk/>
using FinPlusAssembler;
using FinPlusInterfaces;

namespace FinPlusCompView
{
    public sealed class  FinPlusConnectService:FinPlusControl, IFinPlusConnect
    {
        [State(Test = true)]
        public override bool IsValid { get; set; }
        [State(Test = true)]
        public override string TestString { get { return Adapter.ToString(); } }
        [State(Test = true)]
        public bool CanWrite { get { return _canWrite; } }
        public override IPods Adapter { get { return _conn.GetPods(_serviceKey); } }
        private IServiceConn _conn;
        private readonly string _group, _serviceName, _serviceKey, _keyFormat = "[group],[type],[where]", _query;
        private bool _canWrite = false;

        //construct
        public FinPlusConnectService(string serviceName, string serviceType, string query, string keyFormat = null, bool isTransposed = true)
        {
            if (!string.IsNullOrEmpty(keyFormat))
                _keyFormat = keyFormat;

            _conn = IOC.New<IServiceConn>();
            _serviceKey = _conn.Key(_serviceName = serviceName, _query = query, _keyFormat);

            if (!query.RegxTryGet(@"\[*group\]*,(?<result>.*?)\;", out _group))
                throw new ServiceConnException(string.Format("Service type {0} name {1} cant extract group", serviceType, _serviceName));
            
            var perm = Permissions.Get(Common.Group.ToString(), _group);
            if (!perm.CanRead)
                throw new ServiceConnException(string.Format("User {0} permission problem, 'Group {1}", User, _group));           
           
            _canWrite = perm.CanWrite;
            _conn.Connect(Env, Config, User, _serviceKey, serviceType, _query, isTransposed);
            
            IsValid = true;
        }

        //common control interface 
        public override void Dispose()
        {
            if(_conn !=null)
                _conn.Dispose(_serviceKey);
        }

        //public
        public IDPods DPods(){return _conn.GetDPods(_serviceKey);}

        public IPods Pods(){return _conn.GetPods(_serviceKey);}
    }
}


























































































//Copyright2013<jnrton>AllRightsReserved 
//Contact j.nrton@finpus